package com.jn.jackson.views;

import android.util.Log;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jn.jackson.R;
import com.jn.jackson.base.BaseActivity;
import com.jn.jackson.entity.Data;
import com.jn.jackson.entity.People;
import com.jn.jackson.entity.School;
import com.jn.jackson.entity.Student;
import com.jn.jackson.entity.User;
import com.jn.jackson.utils.JsonUtils;

import java.io.IOException;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends BaseActivity {
    private Student mStudent;
    private Student mStudent1;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void init() {
        //objToJson();
        //jsonToObj();
        //objToJson2();
        //jsonToObj2();
        //jsonToObj3();
        //jsonToList();
        //listToJson();
        //streamObjToJson();
        //streamJsonToObj();
        getValueByKey();
    }

    /**
     * 把实体对象转化为json字符串
     *
     * @return
     */
    private String objToJson() {
        String jsonStr = null;
        try {
            mStudent = new Student();
            mStudent.setStudent_code("22");
            mStudent.setStudent_id(1);
            mStudent.setStudent_name("刘老八");
            mStudent.setUsername("abcdef");
            mStudent.setPassword("123456");
            mStudent.setClass_name("计算机10班");
            ObjectMapper objectMapper = new ObjectMapper();
            jsonStr = objectMapper.writeValueAsString(mStudent);
            Log.d("asdf", "objToJson : " + jsonStr);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return jsonStr;
    }

    /**
     * json字符串转化为实体对象
     */
    private void jsonToObj() {
        try {
            String jsonStr = objToJson();
            ObjectMapper objectMapper = new ObjectMapper();
            mStudent1 = objectMapper.readValue(jsonStr, Student.class);
            Log.d("asdf", "jsonToObj = " + mStudent1.toString());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 复杂对象转化为json字符串
     */
    private void objToJson2() {
        try {
            Student student = new Student();
            student.setStudent_code("22");
            student.setStudent_id(1);
            student.setStudent_name("刘老八");
            student.setUsername("abcdef");
            student.setPassword("123456");
            student.setClass_name("计算机10班");

            Student student2 = new Student();
            student2.setStudent_code("22");
            student2.setStudent_id(1);
            student2.setStudent_name("刘老八");
            student2.setUsername("abcdef");
            student2.setPassword("123456");
            student2.setClass_name("计算机10班");

            List<Student> students = new ArrayList<>();
            students.add(student);
            students.add(student2);

            School school = new School();
            school.setName("吉林农业科技学院");
            school.setAddress("吉林市");
            school.setStudents(students);

            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = objectMapper.writeValueAsString(school);
            Log.d("asdf", "school = " + jsonStr);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 复杂json转化为实体对象
     */
    private void jsonToObj2() {
        try {
            String jsonStr = getJson("school.json");
            ObjectMapper objectMapper = new ObjectMapper();
            School school = objectMapper.readValue(jsonStr, School.class);
            Log.d("asdf", "jsonToObj = " + school.toString());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    private void jsonToObj3() {
        try {
            String jsonStr = getJson("student_list.json");
            ObjectMapper objectMapper = new ObjectMapper();
            Data student_list = objectMapper.readValue(jsonStr, Data.class);
            Log.d("asdf", "jsonToObj = " + student_list.getData().getGrade2021());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * json数组转化为List
     */
    private List<People> jsonToList() {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = getJson("peoples.json");

            List<People> list = objectMapper.readValue(
                    jsonStr,
                    new TypeReference<List<People>>() {
                    } // 明确泛型类型
            );

            for (People people : list) {
                Log.d("asdf", "people = " + people.toString());
            }
            return list;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    private void listToJson() {
        try {
            List<People> peopleList = jsonToList();
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = objectMapper.writeValueAsString(peopleList);
            Log.d("asdf", "jsonStr = " + jsonStr.toString());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 流式API 对象转化为json字符串，适合大对象的转化
     */
    private String streamObjToJson() {
        try {
            User user = new User("Tom", 22, new Date());
            // 1. 创建 JsonFactory 和 JsonGenerator
            JsonFactory factory = new JsonFactory();
            StringWriter writer = new StringWriter(); // 用于存储生成的 JSON
            JsonGenerator generator = factory.createGenerator(writer); //生成器

            // 2. 配置格式化（可选：缩进美化输出）
            generator.useDefaultPrettyPrinter();

            // 3. 开始生成 JSON 对象（{）
            generator.writeStartObject();

            // 4. 写入字段（键值对）
            generator.writeStringField("name", user.getName()); // 字符串字段
            generator.writeNumberField("age", user.getAge());   // 数字字段

            // 日期字段：自定义格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
            generator.writeStringField("registerDate", sdf.format(user.getRegisterDate()));

            // 5. 结束 JSON 对象（}）
            generator.writeEndObject();

            // 6. 关闭资源
            generator.close();

            // 7. 返回生成的 JSON 字符串
            String jsonStr = writer.toString();
            Log.d("asdf", "streamObjToJson : " + jsonStr);
            return jsonStr;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void streamJsonToObj() {
        try {
            String json = streamObjToJson();//JsonUtils.getJsonFromAssets(this, "user.json");
            // 1. 创建 JsonFactory 和 JsonParser
            JsonFactory factory = new JsonFactory();
            JsonParser parser = factory.createParser(json);

            // 2. 初始化对象字段
            String name = null;
            int age = 0;
            Date registerDate = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");

            // 3.先移动到对象开始 token（{）
            if (parser.nextToken() != JsonToken.START_OBJECT) {
                throw new IOException("Expected START_OBJECT");
            }

            // 4. 遍历 JSON token
            while (parser.nextToken() != JsonToken.END_OBJECT) {
                // 获取当前字段名
                String fieldName = parser.currentName();
                Log.d("asdf", "streamObjToJson fieldName : " + fieldName);
                // 移动到字段值
                parser.nextToken();

                // 根据字段名解析值
                switch (fieldName) {
                    case "name":
                        name = parser.getValueAsString(); // 解析字符串
                        break;
                    case "age":
                        age = parser.getValueAsInt(); // 解析整数
                        break;
                    case "registerDate":
                        registerDate = sdf.parse(parser.getValueAsString()); // 解析日期
                        break;
                    default:
                        // 忽略未知字段
                        parser.skipChildren();
                        break;
                }
            }

            // 5. 关闭资源
            parser.close();

            // 6. 构建并返回对象
            User user =  new User(name, age, registerDate);
            Log.d("asdf", "streamObjToJson : " + user.toString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    private void getValueByKey() {
        String jsonStr = getJson("news.json");
        List<String> values = JsonUtils.getKeyRecursively(jsonStr, "detail");
        Log.d("asdf", "getValueByKey value ==== " + values.get(0));
    }

    private String getJson(String name) {
        String json = JsonUtils.getJsonFromAssets(this, name);
        Log.d("asdf", "getJson = " + json);
        return json;
    }
}